//
//  BaseVC.m
//  PostDelivery
//
//  Created by wmz on 2020/6/18.
//  Copyright © 2020 wmz. All rights reserved.
//

#import "BaseVC.h"
#import "IQKeyboardManager.h"
@interface BaseVC ()

@property (nonatomic, strong) BaseTextField *codeTextField;

@property (nonatomic,   copy) NavClickBlock leftButtonClickHandle;

@property (nonatomic,   copy) NavClickBlock rightButtonClickHandle;

@end

@implementation BaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //self.view.backgroundColor = wColor_bg;
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hd_noAction) name:UIViewControllerUpdateUINo object:nil];
    [self hd_setupViews];
    [self hd_bindViewModel];
    [self hd_setupNavigation];
    [self hd_getNewData];
    //[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}

- (void)hd_noAction{
    [self hd_getNewData];
    [self hd_getWillData];
}

///响应链操作 子类可继承 可以放一些频率比较高的事件
- (void)respondEvent:(NSObject<GNEvent> *)event{
    ///返回
    if ([event.key isEqualToString:@"backAction"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    ///前往登录
    else if ([event.key isEqualToString:@"pushLoginAction"]) {
        [PostWindow toLogonAction:NO];
    }
    ///刷新
    else if ([event.key isEqualToString:@"reloadCell"]) {
        if ([self valueForKey:@"tableView"]) {
            GNTableView *tableView = [self valueForKey:@"tableView"];
            if ([tableView isKindOfClass:GNTableView.class]) {
                [tableView reloadData];
            }
        }
    }
    ///复制
    else if ([event.key isEqualToString:@"copyAction"]) {
        if (event.info[@"data"]) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            [pasteboard setString:event.info[@"data"]];
            PostSuccessView(@"复制成功", self.view)
        }
    }
}

- (void)hd_setupViews {
}

- (void)hd_bindViewModel {
}

- (void)hd_setupNavigation {
    [self customBack:PostBackIcon];
}

- (void)hd_getNewData{
}

- (void)hd_getWillData{
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([self customNaviLineHidden]) {
        [self seekLineImageViewOn:self.navigationController.navigationBar].hidden = YES;
    }
    if ([self enableKey]) {
        [[IQKeyboardManager sharedManager] setEnable:NO];
        [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    }
    [self hd_getWillData];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if ([self enableKey]) {
        [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
        [[IQKeyboardManager sharedManager] setEnable:YES];
    }
    
    if ([self customNaviLineHidden]) {
        [self seekLineImageViewOn:self.navigationController.navigationBar].hidden = NO;
    }
    
    if(self.openInteractivePop&&[self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
         self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.navigationController.viewControllers.count == 1) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    } else {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
    if(self.openInteractivePop&&[self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
         self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (UIButton*)setLeftButton:(id)any handle:(NavClickBlock)block{
    if (!any) return nil;
    UIButton *btn = [self getButton:any];
    [btn addTarget:self action:@selector(onLeftBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = barItem;
    self.leftButtonClickHandle = block;
    return btn;
}

- (void)setBackButton:(NSString*)name handle:(NavClickBlock)block{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationController.navigationBar.backIndicatorImage = [[UIImage imageNamed:name] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationController.navigationBar.backIndicatorTransitionMaskImage = [[UIImage imageNamed:name] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.backBarButtonItem = backItem;
}

- (UIButton*)setRightButton:(id)any handle:(NavClickBlock)block{
    if (!any) return nil;
    UIButton *btn = [self getButton:any];
    [btn addTarget:self action:@selector(onRightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = barItem;
    self.rightButtonClickHandle = block;
    return btn;
}

- (void)onLeftBtnAction:(UIButton*)sender{
    if (self.leftButtonClickHandle)
        self.leftButtonClickHandle(sender);
}

- (void)onRightBtnAction:(UIButton*)sender{
    if (self.rightButtonClickHandle)
        self.rightButtonClickHandle(sender);
}

- (UIButton*)getButton:(id)any{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    if ([any isKindOfClass:[NSString class]]) {
        [btn.titleLabel setFont:wFontSize(14.0f)];
        [btn setTitleColor:wColor_orange forState:UIControlStateNormal];
        [btn setTitle:any forState:UIControlStateNormal];
        [btn sizeToFit];
    }else if ([any isKindOfClass:[UIImage class]]){
        UIImage *image = (UIImage*)any;
        [btn setImage:image forState:UIControlStateNormal];
        CGFloat width = MAX(image.size.width, 25);
        width = MIN(width, 30);
        CGFloat height = MAX(image.size.height, 25);
        height = MIN(height, 30);
        btn.frame = CGRectMake(0.0, 0.0, width, height);
    }
    return btn;
}

- (BOOL)naviTranslate{
    return NO;
}

- (BOOL)needLogin {
    return false;
}

- (SAViewControllerNaviType)customNaviType{
    return SAViewControllerNaviTypeNormal;;
}

- (UIColor *)customNaviColor{
    return wColor_white;
}

- (BOOL)customNaviLineHidden{
    return NO;
}

- (BOOL)enableKey{
    return NO;
}

- (void)dealloc{
    NSLog(@"%@ dealloc",NSStringFromClass(self.class));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/// 查找导航栏下的横线
- (UIImageView *)seekLineImageViewOn:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) return (UIImageView *)view;
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self seekLineImageViewOn:subview];
        if (imageView) return imageView;
    }
    return nil;
}

- (UIView*)seekNaviContentView{
    NSMutableArray *loop= [NSMutableArray new];
    [loop addObject:[self.navigationController.navigationBar subviews]];
    while (loop.count) {
        NSArray *arr = loop.lastObject;
        [loop removeLastObject];
        for (NSInteger i = arr.count - 1; i >= 0; i--) {
            UIView *view = arr[i];
            [loop addObject:view.subviews];
            if ([[UIDevice currentDevice].systemVersion intValue] >= 12 && [[UIDevice currentDevice].systemVersion intValue] < 13){
                if ([NSStringFromClass([view class]) isEqualToString:@"UIVisualEffectView"]) {
                    return view;
                }
            }else{
                if ([NSStringFromClass([view class]) isEqualToString:@"_UIBarBackground"]||[NSStringFromClass([view class]) isEqualToString:@"_UINavigationBarBackground"]) {
                    return view;
                }
            }
        }
    }
    return nil;
}

- (UIView *)customNavi{
    if (!_customNavi) {
        @HDWeakify(self);
        _customNavi = UIView.new;
        _customNavi.add_constraints(^(MASConstraintMaker * _Nullable make) {
            make.left.mas_equalTo(0);
            make.height.mas_equalTo(44);
            make.top.mas_equalTo(PostNavigationStatusBar);
        }, self.view);
        
        Add_Button(^(UIButton * _Nonnull button) {
            button.add_image([UIImage imageNamed:@"store_3"])
            .add_event(^(UIView * _Nonnull sender) {
                @HDStrongify(self);
                [self respondEvent:[GNEvent eventKey:@"backAction"]];
            })
            .add_constraints(^(MASConstraintMaker * _Nullable make) {
                make.left.mas_equalTo(10);
                make.right.mas_equalTo(-10);
                make.centerY.mas_equalTo(0);
            }, self->_customNavi);
        });
    
    }
    return _customNavi;
}

@end
